import { ChangeDetectionStrategy, ChangeDetectorRef, Component } from '@angular/core';
import { ICellRendererAngularComp } from '@ag-grid-community/angular';
import { ICellRendererParams } from '@ag-grid-community/core';
import { deepClone } from '../../../utils/utils';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { ApesModalService } from '@shared/apes/modal';
import { parseDurationToMs } from '@angular/service-worker/config/src/duration';

@Component({
  selector: 'apes-cell-switch',
  template: `
    <div class="apes-cell-switch" *ngIf="showGroup">
      <ng-container *ngFor="let check of list; index as i;">
        <apes-switch [(ngModel)]="check.checked" [apesDisabled]="disabled"
                     apesCheckedChildren="{{check.select}}"
                     apesUnCheckedChildren="{{check.unSelect}}" (ngModelChange)="setNode(i, $event)"></apes-switch>
      </ng-container>
      <ng-template #checkedTemplate><i apes-icon apesType="check"></i></ng-template>
      <ng-template #unCheckedTemplate><i apes-icon apesType="close"></i></ng-template>
    </div>
  `,
  styles: [`
    .apes-cell-switch {
      text-align: center;
    }

    apes-switch {
      margin-right: 2px;
    }
  `],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class RenderSwitchComponent implements ICellRendererAngularComp {

  params: ICellRendererParams;
  disabled = true;
  colDef = '';
  list = [];
  data = {};
  confirm: any;
  ctx: any = {};
  showGroup : boolean = true;

  constructor(
    protected expressionService: ExpressionService,
    private cd: ChangeDetectorRef,
    private modalService: ApesModalService) {
  }


  agInit(params: ICellRendererParams): void {
    this.params = params;
    this.ctx = params.context;

    if (params.hasOwnProperty('colDef')) {
      this.list = deepClone(params.colDef['list']);
      this.disabled = params.colDef['cellDisabled'];
      // this.confirm = params.colDef['confirm'];
      this.data = deepClone(params.data);
    } else {
      this.list = deepClone(params.column['colDef']['list']);
      this.disabled = params.column['colDef'].cellDisabled;
      // this.confirm = params.column['colDef'].confirm;
      this.data = deepClone(params.node.data);
    }
    if (params.hasOwnProperty('value')) {
      this.list = params.value;
    }

    if(params.node.hasOwnProperty('group') && params.node.group){
      this.showGroup = false;
    }

    if (this.data) {
      this.list.forEach((item) => {
        if (this.data.hasOwnProperty(item.key)) {
          item.checked = this.data[item.key];
        }
        this.params.node.setDataValue(item.key, item.checked);
      });
    }
  }

  getValue(): any {
    let result;
    if (this.list.length === 0) {
      result = '';
      this.params.value = [];
    } else {
      result = this.list;
      this.params.value = this.list;
    }
    return result;
  }

  setNode(i, param) {
    let confirm = this.list[i].confirm;
    let trigger = null;
    if (this.list[i].trigger) {
      trigger = this.expressionService.evaluate(this.list[i].trigger, {
        context: this.ctx,
        model: this.ctx['model'],
        data: this.data,
        value: param,
      }, true);
    }
    let show = false;
    if (confirm) {
      if (trigger != null) {
        if (trigger) {
          show = true;
        }
      } else {
        show = true;
      }
    }

    if (show) {
      let title = this.list[i].title;
      let content = this.expressionService.evaluate(this.list[i].content, {
        context: this.ctx,
        model: this.ctx['model'],
        data: this.data,
      });
      this.modalService.confirm({
        apesTitle: title ? title : '',
        apesContent: content ? content : '',
        apesBodyStyle: { textAlign: 'center' },
        apesOkText: '确认',
        apesOkType: 'primary',
        apesOnOk: () => {
          this.updateList(i, param);
        },
        apesCancelText: '取消',
        apesOnCancel: () => {
          this.updateList(i, !param);
        },
      });
    } else {
      this.updateList(i, param);
    }
  }

  updateList(i, boolean) {
    this.list[i].checked = boolean;
    let key = this.list[i].key;
    this.params.node.setDataValue(key, boolean);
    this.params.api.updateRowData(this.params.node.data);
    this.cd.markForCheck();
  }

  refresh(params: any): boolean {
    // params.data[this.params['colDef']] = params.value;
    params.api.refreshCells(params);
    return false;
  }
}
